import fs from 'fs'
import path from 'path'
import json5 from 'json5'

function readPages() {
    const projectRoot = process.cwd()
    const PAGES_JSON_PATH = path.resolve(projectRoot, 'src', 'pages.json')
    const json = fs.readFileSync(PAGES_JSON_PATH, 'utf-8')
    const pages = json5.parse(json)
    const result = []
    
    const push = val => {
        result.push(val + '.vue')
    }
    
    for (let page of pages.pages) {
        push(page.path)
    }
    
    if (pages.subPackages) {
        for (let subPackage of pages.subPackages) {
            for (let page of subPackage.pages) {
                push([subPackage.root, page.path].join('/'))
            }
        }
    }
    
    return result
}

function replacePage(code) {
    const keyword = '</template>'
    const replaceStr = '    <global-component/>\n</template>'
    const lastKeywordIndex = code.lastIndexOf(keyword)
    const keywordBefore = code.slice(0, lastKeywordIndex)
    const keywordAfter = code.slice(lastKeywordIndex + keyword.length)
    return keywordBefore + replaceStr + keywordAfter
}

export default function GlobalComponent() {
    return {
        name: 'global-component-plugin',
        transform(code, path) {
            const pages = readPages()
            for (let page of pages) {
                if (path.endsWith(page)) {
                    return {
                        code: replacePage(code), map: null
                    }
                }
            }
            return {
                code: code, map: null
            }
        }
    }
}
